package com.exam.examtest.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSONObject
import com.exam.examtest.R
import com.exam.examtest.adapter.DataListAdapter
import com.exam.examtest.bean.HttpRecordBean
import com.exam.examtest.contract.MainContract
import com.exam.examtest.presenter.MainPresenter
import com.exam.examtest.util.ActivityStack
import com.exam.examtest.util.ConstantValue
import com.exam.examtest.util.DBHelper
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


/**
 * 主页面
 */
class MainActivity : BaseActivity(), MainContract.View {

    private var exitTime: Long = 0
    private var mTimer: Timer? = null
    private var httpTask: HttpTask? = null

    private var dataList: ArrayList<String>? = null
    private var manager: LinearLayoutManager? = null
    private var mPresenter: MainPresenter? = null
    private var mHandler: Handler? = Handler()
    //private val mRequestCode = 10
    private var isFirst = true //是否第一次请求

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
        checkAndHttp()
    }

    /**
     * 检查并且进行网络请求
     */
    private fun checkAndHttp() {
        val queryRecordData = DBHelper.getInstance().queryRecordByType(ConstantValue.TYPE_RESULT)
        if (queryRecordData.isNotEmpty()) {
            //已经缓存过，启动后显示上次调用的数据
            val latestData = queryRecordData[0]
            setData(latestData.saveUrlOrData)
            mHandler?.postDelayed(Runnable {
                startHttp()
            }, 5000)
        } else {
            startHttp()
        }
    }

    /**
     * 初始化操作
     */
    private fun init() {
        dataList = arrayListOf()
        manager = LinearLayoutManager(this)
        manager!!.orientation = LinearLayoutManager.VERTICAL
        mRecyclerView.layoutManager = manager
        mPresenter = MainPresenter(this, this)

        //点击记录
        tvRecord.setOnClickListener(View.OnClickListener {
            val intent = Intent(this, HttpRecordActivity::class.java)
            startActivity(intent)
            cancelTask()
        })
    }

    /**
     * 开启定时任务
     */
    private fun startHttp() {
        mTimer = Timer()
        httpTask = HttpTask()
        mTimer?.schedule(httpTask, 0, 5000)
    }

    /**
     * 网络请求定时任务
     */
    inner class HttpTask : TimerTask() {
        override fun run() {
            runOnUiThread {
                mPresenter?.httpData()
            }
        }
    }

    override fun handleResult(jsonResult: String?) {
        if (jsonResult != null) {
            if (jsonResult.isNotEmpty()) {
                isFirst = false
                setData(jsonResult)
                //保存请求结果
                val httpRecordBean = HttpRecordBean()
                httpRecordBean.type = ConstantValue.TYPE_RESULT
                httpRecordBean.httpTimeStamp = System.currentTimeMillis()
                httpRecordBean.saveUrlOrData = jsonResult
                DBHelper.getInstance().saveData(httpRecordBean)
            }
        }
    }

    /**
     * 设置列表数据
     */
    private fun setData(json: String?) {
        dataList?.clear()
        val jsonResult = JSONObject.parseObject(json)
        //fastJson解析方法
        for (entry in jsonResult.entries) {
            dataList?.add("" + entry.value)
        }
        val dataListAdapter = DataListAdapter(R.layout.item_main_text, dataList)
        mRecyclerView.adapter = dataListAdapter
    }

    override fun onResume() {
        super.onResume()
        if (!isFirst) {
            startHttp()
        }
    }

    override fun onPause() {
        super.onPause()
        cancelTask()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitApp()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 退出app
     */
    private fun exitApp() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showShortToast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            ActivityStack.getInstance().finishAllActivity()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消任务
        cancelTask()
        //移出Handler
        mHandler?.removeCallbacksAndMessages(null)
    }

    /**
     * 取消任务
     */
    private fun cancelTask() {
        mTimer?.cancel()
        httpTask?.cancel()
    }

}
